﻿using System;
using System.Linq;
using Newtor.Common;

namespace Newtor.VoteMan.Providers
{
    public class LinqVoteOpinionManager : IVoteOpinionManager
    {
        #region IVoteOpinionManager 成员

        public void CreateVoteOpinion(VoteOpinion vo)
        {
            using (VoteDataContext vdc = new VoteDataContext())
            {
                try
                {
                    var existedVo = (from o in vdc.VoteOpinion
                                     where o.ItemId == vo.ItemId && o.Name == vo.Name
                                     select o).First();
                    if (existedVo != null)
                    {
                        vo.OpinionId = existedVo.OpinionId;
                        throw new NewtorException(ExceptionType.ObjectHasExisted);
                    }
                }
                catch (InvalidOperationException)
                {
                    vdc.VoteOpinion.InsertOnSubmit(vo);
                    vdc.SubmitChanges();
                }
                
                
            }
        }

        public VoteOpinion GetVoteOpinion(Guid voId)
        {
            using (VoteDataContext vdc = new VoteDataContext())
            {
                try
                {
                    return vdc.VoteOpinion.Single(vo => vo.OpinionId == voId);
                }
                catch (InvalidOperationException)
                {
                    return null;
                }
            }
        }

        public void DeleteVoteOpinion(Guid voId)
        {
            using (VoteDataContext vdc = new VoteDataContext())
            {
                try
                {
                    var vo = vdc.VoteOpinion.Single(v => v.OpinionId == voId);
                    vdc.VoteOpinion.DeleteOnSubmit(vo);
                }
                catch (InvalidOperationException)
                {
                    return;
                }
                vdc.SubmitChanges();
            }
        }

        public VoteOpinion[] GetOpinionsByItemId(Guid itemId)
        {
            using (VoteDataContext vdc = new VoteDataContext())
            {
                try
                {
                    return vdc.VoteItem.Single(vi => vi.ItemId == itemId).Opinions.ToArray();
                }
                catch (InvalidOperationException)
                {
                    return new VoteOpinion[] { };
                }
            }
        }

        #endregion
    }
}
